JSON (JavaScript Object Notation) is a lightweight data-interchange format which is easy for to read and write, for both people and machines. It is built on two basic structures:
- A collection of name/value pairs, called a ds_map in GameMaker Studio 2 but also known as a "dictionary" or "object".
- An ordered list of values, called a ds_list in GameMaker Studio 2 but this can also be called an "array" or "sequence".
json_encode takes a ds_map that you have previously created and encoded as a JSON string which you can then use as (for example) part of an http_post_string() call, or so it can be stored externally, written to a file.
NOTE: The hierarchal functionality of JSON is available through special ds_map and ds_list functions, so you are able to encode sub-lists and maps.IMPORTANT: You cannot have 64bit numbers in your JSON, as they will not work correctly due them not being handled by the JSON format.
json_encode(map)
Argument | Description |
---|---|
map | a ds_map with the information to encode |
string
var hiscore_map, i, str;
hiscore_map = ds_map_create();
for (i = 0; i < 10; i ++;)
{
ds_map_add(hiscore_map, name[i], score[i]);
}
str = json_encode(hiscore_map);
get[0] = http_post_string("http://www.angusgames.com/game?game_id="
+ string(global.game_id), str)
ds_map_destroy(hiscore_map);
The above code creates a ds_map and then loops through the name and score arrays, adding each key/value pair to the new map. Next, this map is encoded using json_encode and stored as a string in the variable "str". This string is then sent to a web server using http_post_string and the ds_map is destroyed to prevent a memory leak as it is no-longer needed.